package sourceNsink;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class DataSource implements Runnable{

	private volatile boolean running;
	DatagramSocket ds;
	DatagramPacket dp;
	private int periodMsec;
	private final int PORT;
	private String message;
	byte content[] = new byte[24];
	private boolean socketClosed = false;
	
	public DataSource(String message, int period, int port){
		this.PORT = port;
		this.message = message;
		this.running = true;
		this.periodMsec = period;
		System.out.println("Kommunikation wird erstellt....");
		try {
			ds = new DatagramSocket();
			for(int i = 0; i < 24 && i<message.length(); i++){		//String der message fest als content vorgeben
				content[i] = message.getBytes()[i];
			}
			dp = new DatagramPacket(content, content.length, InetAddress.getByName("localhost"), PORT);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	
	public void run() {
		System.out.println("DataSource laeuft und verschickt alle " + periodMsec + " Millisekunden eine Nachricht!");
		while(running){
			
			try {
				if(!socketClosed){
					ds.send(dp);
				}else{
					ds.close();
				}
				//System.out.println("\nDS: Sendung abgesetzt\n");
				Thread.sleep(periodMsec);	//vorgegebene Zeit warten, bis n�chste Daten gesendet werden sollen
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
				
		}
	}
	
	public void terminate(){

		this.socketClosed = true;
		this.running = false;
		System.out.println("DataSource...");
	}
	
}
